import com.bee.剑指offer.反转链表;

/**
 * 反转部分链表
 * 1->2->3->4->5
 * 开始 2 结束 4
 * <p>
 * 反转之后：
 * 1->4->3->2->5
 */
public class LinkeRever {

    public static ListNode reverse(ListNode head, int first, int last) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dum = head;
        ListNode cur = head;
        ListNode pre = null;
        int index = 2;
        ListNode firstNode = null;
        ListNode lastNode = null;
        while (cur != null) {
            firstNode = cur;
            cur = cur.next;
            lastNode = cur;
            if (index == first) {
                break;
            }
            index++;
        }

        while (cur != null && index <= last) {
            index++;
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        firstNode.next = pre;
        lastNode.next = cur;
        return dum;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode reverse = reverse(head, 4, 5);
        while (reverse != null) {
            System.out.println(reverse.val);
            reverse = reverse.next;
        }
    }

    public static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
